# -*- coding: utf-8 -*-
# owner: shenyi
# src/api/instance.py

from fastapi import APIRouter, HTTPException
from src.services.instance import InstanceService
from src.models.instance import (
    CreateInstanceRequest,
    DeleteInstanceRequest,
    QueryInstanceRequest
)
from src.models.responses import (
    CreateResponse,
    DeleteResponse,
    InstanceListResponse
)
from src.core.api_reponse import ApiResponse

router = APIRouter(prefix="/instances", tags=["instances"])

@router.post("/", response_model=ApiResponse[CreateResponse], summary="创建实例")
async def create_instance(request: CreateInstanceRequest):
    """
    创建云服务器实例
    
    Args:
        request: 创建实例请求参数
        
    Returns:
        ApiResponse[CreateResponse]: 创建结果响应
    """
    try:
        service = InstanceService()
        response = await service.create_instance(request)
        return ApiResponse.success(data=response)
    except Exception as e:
        return ApiResponse.error(message=str(e))

@router.delete("/{instance_id}", response_model=ApiResponse[DeleteResponse], summary="删除实例")
async def delete_instance(instance_id: str, request: DeleteInstanceRequest = None):
    """
    删除指定的云服务器实例
    
    Args:
        instance_id: 实例ID
        request: 删除实例请求参数
        
    Returns:
        ApiResponse[DeleteResponse]: 删除结果响应
    """
    try:
        # 如果没有提供request，则创建一个默认的
        if request is None:
            request = DeleteInstanceRequest(instance_id=instance_id)
        elif request.instance_id != instance_id:
            # 如果URL中的instance_id和request中的不一致，以URL中的为准
            request.instance_id = instance_id
            
        service = InstanceService()
        response = await service.delete_instance(request)
        return ApiResponse.success(data=response)
    except Exception as e:
        return ApiResponse.error(message=str(e))

@router.get("/", response_model=ApiResponse[InstanceListResponse], summary="获取实例列表")
async def list_instances(request: QueryInstanceRequest = None):
    """
    获取云服务器实例列表
    
    Args:
        request: 查询实例请求参数
        
    Returns:
        ApiResponse[InstanceListResponse]: 实例列表响应
    """
    try:
        if request is None:
            request = QueryInstanceRequest()
            
        service = InstanceService()
        response = await service.list_instances(request)
        return ApiResponse.success(data=response)
    except Exception as e:
        return ApiResponse.error(message=str(e))